package com.assets.Receive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Adapter.Input_Adapter_item1;
import com.assets.Adapter.Public_list_item_Adapter;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.Input_item1;
import com.assets.bean.ReceiveBeanNew2023;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Receives;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.ReceivesReapply;
import com.assets.util.LogUtil;
import com.assets.util.MyOkHttp;
import com.assets.util.TrustAllCerts;
import com.google.gson.Gson;
import com.hb.dialog.dialog.LoadingDialog;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 领用详情
 */

public class Receive_issued extends Activity {

    private static final String TAG = "领用详情页面";
    private TextView receivesDept, receivesUser, reapplyPlace, receivesDate, receivesRemark;
    private ListView issued_lv;
    //领用部门，领用人，申请时间，领用时间，备注
    private String receivesId;
    private TextView state_list;
    private ImageView fh;
    private String zt;
    LoadingDialog loadingDialog;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();//全部
    private List<Input_item1> data = new ArrayList<>();
    private String url = "http://" + Url.IP + "/api/receivesQueryById";
    private String assetName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receive_issued);
        inview();
    }

    private void load() {
        new Thread() {
            @Override
            public void run() {

//                List<ReceivesReapply> receivesReapplyList = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                Log.d(TAG, "run: " + receivesId);

                Receives allReceives = MyDataBase.init(Receive_issued.this).receivesDao().getAllReceives(receivesId);

//                Log.d("这个是详情组装的数据", "资产: " + receivesReapplyList.toString());
                map.put("receivesDept", allReceives.getReceivesDept());
                map.put("receivesRemark", allReceives.getReceivesRemark());
                map.put("receivesId", allReceives.getReceivesId());

                map.put("receivesUser", allReceives.getReceivesUser());
                map.put("receivesDate", allReceives.getReceivesDate());
                map.put("place", allReceives.getPlace());

//                List<ReceivesDetail> receivesDetailList = MyDataBase.init(Receive_issued.this).receivesDetailDao().getReceivesDetailById(Long.valueOf(receivesId));
//
//                for (ReceivesDetail receivesDetail : receivesDetailList) {
//                    Log.d(TAG, "assetid: " + receivesDetail.getAssetId());
//                    ReceivesReapply allByIds = MyDataBase.init(Receive_issued.this).receivesReapplyDao().getAllByIds(receivesId);
////                    Asset asset = MyDataBase.init(Receive_issued.this).assetDao().queryAllByNumber(receivesDetail.getAssetId());
////                    Log.d(TAG, "asset: " + asset);
//                    receivesReapplyList.add(allByIds);
//                }

                List<ReceivesReapply> receivesReapplyList = MyDataBase.init(Receive_issued.this).receivesReapplyDao().getNameById(receivesId);


                //                assets = MyDataBase.init(Receive_issued.this).assetDao().queryAllByNumber(Long.valueOf(receivesDetailById.getAssetId()));
//
                map.put("assets", receivesReapplyList);
                Log.d(TAG, "asset: " + new Gson().toJson(receivesReapplyList));


//                LogUtil.e("map","数据Map: " + new Gson().toJson(assets));
//                我们采取分段打印日志的方法：当长度超过4000时，我们就来分段截取打印
                //剩余的字符串长度如果大于4000


//
                String responseData = MyOkHttp.getInstance().getGson().toJson(map);
////
//                Log.d("这个是详情组装的数据", "responseData: " + responseData);
                showResponse(responseData);
//                try {
//                    OkHttpClient client = new OkHttpClient
//                            .Builder()
//                            .hostnameVerifier(new AllowAllHostnameVerifier())
//                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                            .readTimeout(500, TimeUnit.SECONDS)
//                            .build();
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("receivesId", receivesId)
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody).build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    showResponse(responseData);//解析
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        }.start();
    }

    private void showResponse(final String responseData) {
        Gson gson = new Gson();
        ReceiveBean bean2 = gson.fromJson(responseData, ReceiveBean.class);
        ReceiveBeanNew2023 bean = gson.fromJson(responseData, ReceiveBeanNew2023.class);
        Log.d(TAG, "bean: " + new Gson().toJson(bean));
        if (zt.contains("已发放")) {

            Log.d(TAG, "已经发放");
            for (ReceiveBeanNew2023.ReceivesReapplyDTO reapplyBean : bean.getAssets()) {
                assetName = reapplyBean.getName();
                String deptId = reapplyBean.getPlace();
                String assetNumber = reapplyBean.getNum();
                String userId = reapplyBean.getUser();
                String model = reapplyBean.getIsaudit();
                String type = reapplyBean.getIsaudit();
                String image = "";
                data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, ""));
            }
            issued_lv.setOnItemClickListener((parent, view, position, id) -> {
                Toast.makeText(this, "当前资产已全部领用", Toast.LENGTH_SHORT).show();
            });
            Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Receive_issued.this, R.layout.input_adapter_item, data);
            runOnUiThread(() ->
                    issued_lv.setAdapter(adapter_item)
            );
        } else if (zt.equals("待发放") || zt.equals("部分发放")) {
            LogUtils.d("待发放/部分发放");
            for (int i = 0; i < bean.getAssets().size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("odd_tv", "资产编号");
                map.put("creator_tv", "应发数量");//数量  待发数量
                map.put("sum_tv", "资产");
                map.put("state_tv", "状态");
                map.put("scope_tv", "申请数量");
                map.put("Date_created_tv", "使用位置");
                map.put("Inventory_date_tv", "使用人");//改使用人
                String zt = "";
//                if (TextUtils.isEmpty(asset.getStatus())) {
//
//                } else if (asset.getStatus().equals("-")) {
//                    zt = "未审核";
//                } else if (asset.getStatus().equals("1")) {
//                    zt = "通过";
//                    if (asset.getStatus().equals("3") {
//                        zt = "已发放";
//                    }
//                } else if (asset.getIsaudit().equals("0")) {
//                    zt = "不通过";
//                }

                map.put("scope", bean.getAssets().size());//申请数量
                map.put("state", "0".equals(bean.getAssets().get(i).getIsput()) ? "待发放" : "已全部发放"); //状态
                map.put("odd", receivesId); //单号
//                Log.d(TAG, "odd: " + MyDataBase.init(Receive_issued.this).receivesDetailDao().getNameById(bean.getAssets().get(i).getAssetNumber()).get(i).getReceivesId().toString());
                map.put("Inventory_date", MyDataBase.init(Receive_issued.this).userDao().getNameByIds(bean.getAssets().get(i).getUser()));//userList.get(i).getAssetName(); 理由
                map.put("Date_created", MyDataBase.init(Receive_issued.this).placeDao().getNameById(bean.getAssets().get(i).getPlace())); //使用位置
                map.put("creator", bean.getAssets().get(i).getNum());//待领用数量
                map.put("sum", bean.getAssets().get(i).getName());//名称
                map.put("reapplyId", receivesId); //位置
                list.add(map);


            }
            Log.d(TAG, "list: " + list);
            //适配器，刚刚重写的！
            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(Receive_issued.this, list);
            issued_lv.setOnItemClickListener((parent, view, position, id) -> {
                if (zt.equals("待发放") || zt.equals("部分发放")) {
                    if (!list.get(position).get("state").equals("已发放")) {
                        Intent intent = new Intent(this, Grant_rfid.class);
                        intent.putExtra("coding_name", getIntent().getStringExtra("coding_name"));
                        intent.putExtra("status", getIntent().getStringExtra("status"));
                        intent.putExtra("reapplyId", list.get(position).get("reapplyId").toString());
                        intent.putExtra("sum", list.get(position).get("creator").toString());
                        intent.putExtra("name", list.get(position).get("sum").toString());

                        intent.putExtra("position", position);
                        startActivityForResult(intent, 1);
                    }
                }else {
                    Toast.makeText(this, "当前资产已全部领用", Toast.LENGTH_SHORT).show();
                }
            });
            runOnUiThread(() ->
                    issued_lv.setAdapter(re_ad)
            );
//            Toast.makeText(this, "当前已全部领用完成!", Toast.LENGTH_SHORT).show();
        } else {
            LogUtils.d("申请中/审核没通过");
            for (int i = 0; i < bean.getAssets().size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("odd_tv", "资产编号");
                map.put("creator_tv", "数量");//数量
                map.put("sum_tv", "资产");
                map.put("state_tv", "状态");
                map.put("scope_tv", "申请数量");
                map.put("Date_created_tv", "使用位置");
                map.put("Inventory_date_tv", "使用人");//改使用人
                String zt = "";
//                if (TextUtils.isEmpty(asset.getIsaudit())) {
//                } else if (asset.getIsaudit().equals("-")) {
//                    zt = "未审核";
//                } else if (asset.getIsaudit().equals("1")) {
//                    zt = "通过";
//                } else if (asset.getIsaudit().equals("0")) {
//                    zt = "不通过";
//                }
//                map.put("scope", zt);
//                map.put("state", asset.getUnaudit());
//                map.put("odd", asset.getAssetNumber());
//                map.put("Inventory_date", asset.getUser());//userList.get(i).getAssetName(); 理由
//                map.put("Date_created", asset.getPlace());
//                map.put("creator", asset.getNum());//数量
//                map.put("sum", asset.getName());
                map.put("scope", bean.getAssets().size());//申请数量
//                map.put("state", "0".equals(bean.getAssets().get(i).getIsput()) ? "待发放" : "已全部发放");
                map.put("state", "0".equals(bean.getAssets().get(i).getIsput()) ? "待发放" : "已全部发放"); //状态              状态
                map.put("odd", receivesId); //单号
//                Log.d(TAG, "odd: " + MyDataBase.init(Receive_issued.this).receivesDetailDao().getNameById(bean.getAssets().get(i).getAssetNumber()).get(i).getReceivesId().toString());
                map.put("Inventory_date", MyDataBase.init(Receive_issued.this).userDao().getUserById(bean.getAssets().get(i).getUser()) == null ? "暂无此人":MyDataBase.init(Receive_issued.this).userDao().getUserById(bean.getAssets().get(i).getUser()).getName()/*MyDataBase.init(Receive_issued.this).userDao().getNameByIds(bean.getAssets().get(i).getUser())*/);//userList.get(i).getAssetName(); 理由
                map.put("Date_created", MyDataBase.init(Receive_issued.this).placeDao().getNameById(bean.getAssets().get(i).getPlace())); //使用位置
                map.put("creator", bean.getAssets().get(i).getNum());//待领用数量
                map.put("sum", bean.getAssets().get(i).getName());//名称
                map.put("reapplyId", receivesId); //位置
                list.add(map);
            }
            issued_lv.setOnItemClickListener((parent, view, position, id) -> {
                Toast.makeText(this, "当前资产已全部领用", Toast.LENGTH_SHORT).show();
            });
            //适配器，刚刚重写的！
            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(Receive_issued.this, list);
            runOnUiThread(() ->
                    issued_lv.setAdapter(re_ad)
            );
        }

        runOnUiThread(() -> {
            loadingDialog.dismiss();
            LogUtils.d(zt + "领用详情" + gson.toJson(bean));
            receivesDept.setText(MyDataBase.init(Receive_issued.this).deptDao().getNameById(bean.getReceivesDept()));
            receivesUser.setText(MyDataBase.init(Receive_issued.this).userDao().getNameByIds(bean.getReceivesUser()));
            reapplyPlace.setText(MyDataBase.init(Receive_issued.this).placeDao().getNameById(bean.getPlace()));
            if (!TextUtils.isEmpty(bean.getReceivesDate())) {
                receivesDate.setText(bean.getReceivesDate().substring(0, 10));
            }
            receivesRemark.setText(bean.getReceivesRemark());
        });
    }

    private void go(final String responseData) {

        Gson gson = new Gson();
        ReceiveBean bean = gson.fromJson(responseData, ReceiveBean.class);
        LogUtils.d("已发放");
        if (zt.contains("已发放")) {
            for (ReceiveBean.AssetsBean asset : bean.getAssets()) {
                String assetName = asset.getAssetName();
                String deptId = asset.getDeptId();
                String assetNumber = asset.getAssetNumber();
                String userId = asset.getUserId();
                String model = asset.getModel();
                String type = asset.getPlace();
                String image = asset.getImage();
                if (!TextUtils.isEmpty(image)) {
                    image = "http://" + Url.IP + image;
                }
                data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, ""));
            }
            Input_Adapter_item1 adapter_item = new Input_Adapter_item1(Receive_issued.this, R.layout.input_adapter_item, data);
            runOnUiThread(() -> issued_lv.setAdapter(adapter_item));
        } else if (zt.equals("待发放") || zt.equals("部分发放")) {
            LogUtils.d("待发放/部分发放");
            for (ReceiveBean.AssetsBean asset : bean.getAssets()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("odd_tv", "资产编号");
                map.put("creator_tv", "待发数量");//数量
                map.put("sum_tv", "资产");
                map.put("state_tv", "状态");
                map.put("scope_tv", "申请数量");
                map.put("Date_created_tv", "使用位置");
                map.put("Inventory_date_tv", "使用人");//改使用人
                String zt = "";
                if (TextUtils.isEmpty(asset.getIsaudit())) {

                } else if (asset.getIsaudit().equals("-")) {
                    zt = "未审核";
                } else if (asset.getIsaudit().equals("1")) {
                    zt = "通过";
                    if (TextUtils.isEmpty(asset.getIsput()) || asset.getIsput().equals("1")) {
                        zt = "已发放";
                    }
                } else if (asset.getIsaudit().equals("0")) {
                    zt = "不通过";
                }

                map.put("scope", asset.getNum());//申请数量
                map.put("state", zt);
                map.put("odd", asset.getAssetNumber());
                map.put("Inventory_date", asset.getUser());//userList.get(i).getAssetName(); 理由
                map.put("Date_created", asset.getPlace());
                map.put("creator", asset.getSum());//待领用数量
                map.put("sum", asset.getName());
                map.put("reapplyId", asset.getId());
                list.add(map);
            }
            //适配器，刚刚重写的！
            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(Receive_issued.this, list);
            issued_lv.setOnItemClickListener((parent, view, position, id) -> {
                if (zt.equals("待发放") || zt.equals("部分发放")) {
                    if (!list.get(position).get("state").equals("已发放")) {
                        Intent intent = new Intent(this, Grant_rfid.class);
                        intent.putExtra("coding_name", getIntent().getStringExtra("coding_name"));
                        intent.putExtra("status", getIntent().getStringExtra("status"));
                        intent.putExtra("reapplyId", (String) list.get(position).get("reapplyId"));
                        intent.putExtra("sum", (String) list.get(position).get("creator"));
                        startActivityForResult(intent, 1);
                    }
                }
            });
            runOnUiThread(() -> issued_lv.setAdapter(re_ad));
        } else {
            LogUtils.d("申请中/审核没通过");
            for (ReceiveBean.AssetsBean asset : bean.getAssets()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("odd_tv", "资产编号");
                map.put("creator_tv", "数量");//数量
                map.put("sum_tv", "资产");
                map.put("state_tv", "反驳理由");
                map.put("scope_tv", "状态");
                map.put("Date_created_tv", "使用位置");
                map.put("Inventory_date_tv", "使用人");//改使用人
                String zt = "";
                if (TextUtils.isEmpty(asset.getIsaudit())) {
                } else if (asset.getIsaudit().equals("-")) {
                    zt = "未审核";
                } else if (asset.getIsaudit().equals("1")) {
                    zt = "通过";
                } else if (asset.getIsaudit().equals("0")) {
                    zt = "不通过";
                }
                map.put("scope", zt);
                map.put("state", asset.getUnaudit());
                map.put("odd", asset.getAssetNumber());
                map.put("Inventory_date", asset.getUser());//userList.get(i).getAssetName(); 理由
                map.put("Date_created", asset.getPlace());
                map.put("creator", asset.getNum());//数量
                map.put("sum", asset.getName());
                list.add(map);
            }
            //适配器，刚刚重写的！
            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(Receive_issued.this, list);
            runOnUiThread(() -> issued_lv.setAdapter(re_ad));
        }

        runOnUiThread(() -> {
            loadingDialog.dismiss();
            LogUtils.d(zt + "领用详情" + gson.toJson(bean));
            receivesDept.setText(bean.getReceivesDept());
            receivesUser.setText(bean.getReceivesUser());
            reapplyPlace.setText(bean.getPlace());
            if (!TextUtils.isEmpty(bean.getReceivesDate())) {
                receivesDate.setText(bean.getReceivesDate().substring(0, 10));
            }
            receivesRemark.setText(bean.getReceivesRemark());
        });

    }

    private void inview() {
        state_list = (TextView) findViewById(R.id.state_list);
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMessage("加载中....");
        loadingDialog.show();
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(v -> finish());
        Intent intent = getIntent();
        receivesId = intent.getStringExtra("coding_name");
        Log.d("这个是什么id", "receivesId: " + receivesId);
        zt = intent.getStringExtra("status");
        if (zt.equals("申请中")) {
            state_list.setText("申请列表");
        }
        if (zt.equals("待发放")) {
            state_list.setText("待发放列表");
        }
        if (zt.equals("已发放")) {
            state_list.setText("已发放列表");
        }
        if (zt.equals("驳回")) {
            state_list.setText("驳回列表");
        }
        issued_lv = (ListView) findViewById(R.id.issued_lv);
        receivesDept = (TextView) findViewById(R.id.receivesDept);
        receivesUser = (TextView) findViewById(R.id.receivesUser);
        reapplyPlace = (TextView) findViewById(R.id.reapplyPlace);
        receivesDate = (TextView) findViewById(R.id.receivesDate);
        receivesRemark = (TextView) findViewById(R.id.receivesRemark);
        load();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 1) {
                finish();
            }
        }
    }
}
